const http = require('http');
const path = require('path');
const fs = require('fs');
const urlib = require('url');
const { filesOutput } = require('../new');
const renderWebLayout = require('./renderWebLayout');
const generate = require('./generate');
const mountScript = require('./mountScript');

const createScriptServer = (opts) => {
  const { config } = require(path.join(global.cwdPath, './.yhpagerc.js'));
  global.config = config;
  const { index } = config;

  mountScript(index);
  const { INSERT_ELE, PORT } = opts;
  return http
    .createServer((req, res) => {
      const { query, pathname } = urlib.parse(req.url);
      if (pathname === '/') {
        const scriptsString = renderWebLayout(INSERT_ELE);
        res.writeHead(200, {
          'Content-Type': 'application/javascript; charset=utf-8',
          'Access-Control-Allow-Origin': '*',
        });
        res.end(scriptsString);
      }

      if (pathname === '/getTemplate') {
        // const config_path = path.join(global.cwdPath, './.yhpagerc.js');
        const [a, b] = query.split('&');
        const [a1, templateType] = a.split('=');
        const [b1, comp] = b.split('=');
        filesOutput(templateType, comp);
        setTimeout(() => {
          const { basePath, storeType } = config;
          const p = path.join(basePath, `./${comp}/index.tsx`);
          const isExsit = fs.existsSync(p);
          res.writeHead(200, {
            'Content-Type': 'application/javascript; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
          });
          const json = JSON.stringify({
            status: Number(isExsit),
            p,
            template: templateType,
          });
          res.end(json);
        }, 1000);
      }

      if (pathname === '/newTemplate') {
        res.writeHead(200, {
          'Content-Type': 'text/html;charset=utf-8',
          'Access-Control-Allow-Origin': '*',
        });
        const html = fs.readFileSync(
          path.join(global.appRoot, './web/newTemplate.html'),
          {
            encoding: 'utf-8',
          }
        );
        res.end(html);
      }

      if (pathname === '/generate') {
        res.writeHead(200, {
          'Content-Type': 'application/json;charset=utf-8',
          'Access-Control-Allow-Origin': '*',
        });
        const arr = [];
        req.on('data', (d) => {
          arr.push(d);
        });
        req.on('end', () => {
          const data = Buffer.concat(arr).toString();
          try {
            const ret = JSON.parse(data);
            const { hbs, events } = ret;
            const e = eval(events);
            generate(hbs, e, (status, newComName, error) => {
              res.end(JSON.stringify({ status, newComName, error }));
            });
          } catch (error) {
            res.end(JSON.stringify({ status: 0, error }));
            console.log('e', error);
          }
        });
        // console.log('req', req.params);
        // console.log('req', req.body);
      }
    })
    .listen(PORT);
};

module.exports = createScriptServer;
